const mysql = require('../lib/mysql');

class Servers {
  constructor(table) {
    this.table = table;
  }
  /**
   * 新增一条数据
   * @param {object} arg 数据对象
   */
  async insert(arg) {
    const sql = 'INSERT INTO ' + this.table + ' SET ?';
    return await mysql.sql(sql, arg, 'insert')
  }
  /**
   * 新增多条数据
   * @param {[array]} arg 数据列表 - 二维数组
   */
  async inserts(arg) {
    const sql = 'INSERT INTO ' + this.table + ' VALUES ?';
    return await mysql.sql(sql, [arg], "insert")
  }
  /**
   * 删除某一条数据
   * @param {object} arg 条件
   */
  async delete(arg) {
    return await mysql.sql('DELETE FROM `' + this.table + '` WHERE ?', arg, "delete")
  }
  /**
   * 修改某一条数据
   * @param {object} arg 条件
   */
  async update(arg) {
    let setObj = {};
    let whereObj = {};
    for (let i in arg) {
      if (!arg.hasOwnProperty(i)) continue;
      if (i === 'id') {
        whereObj[i] = arg[i];
      } else {
        setObj[i] = arg[i];
      }
    }
    let sql = 'UPDATE `' + this.table + '` SET ? WHERE ?'
    return await mysql.sql(sql, [setObj, whereObj], 'update')
  }
  async select() {

  }
  /**
   * 获取某一条数据
   * @param {object} arg 条件
   */
  async find(arg) {
    const sql = 'SELECT * FROM `' + this.table + '` WHERE ?';
    let result = await mysql.sql(sql, arg, 'select');
    result.data = result.data.length > 0 ? result.data[0] : false;
    return result;
  }
}

module.exports = Servers;